<template>
  <div ref="FundsPlanAdd" class="_wz_FundsPlanAdd">
    <Form ref="formAdd" :model="formData" label-position="right" :label-width="130" :rules="ruleValidate">
      <Row>
        <i-col span="24">
          <i-col span="8">
            <FormItem label="计划年份" prop="wzPlanYear">
              <DatePicker v-model="formData.wzPlanYear" type="year" placeholder="请选择年份"></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="运输企业" prop="deptUuid">
              <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" :label-in-value="true" @on-change="deptNameFun" clearable>
                <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
              </i-select>
            </FormItem>
          </i-col>

          <i-col span="8">
            <FormItem label="经费提取标准" prop="planStandardPercent">
              <i-input v-model.number="formData.planStandardPercent" placeholder="请填写费用提取标准" @on-change="planExtractAmountFun" clearable/>
            </FormItem>
          </i-col>
        </i-col>

        <i-col span="8">
          <FormItem label="去年营业额（万）" prop="planIncome">
            <i-input v-model.number="formData.planIncome" placeholder="请填写去年营业额（万）" @on-change="planExtractAmountFun" clearable/>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="计提安全经费（万）" prop="planExtractAmount">
            <i-input v-model.number="formData.planExtractAmount" placeholder="请填写计提安全费用（万）" clearable/>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="登记人" prop="planRegistrantName">
            <i-input v-model="formData.planRegistrantName" placeholder="请填写登记人" clearable/>
          </FormItem>
        </i-col>

        <i-col span="24">
          <FormItem label="图片上传">
            <Upload name="planImgFile" :before-upload="planImgFileFun" action="">
              <Button icon="ios-cloud-upload-outline">选择要上传的图片</Button>
            </Upload>
            <div class="demo-upload-list">
              <viewer style="width: 100%;height: 100%;" v-if="!!planImgFile.imgUrl">
                <img :src="planImgFile.imgUrl" @error="public.imgDispose">
              </viewer>
            </div>
          </FormItem>
        </i-col>
      </Row>

      <Card :bordered="true" style="margin:0 0 10px;">
        <p slot="title">安全经费名目<span style="color:#2d8cf0;margin: 0 0 0 10px;">实际提取安全经费数额: {{!!formData.planActualAmount?formData.planActualAmount:0}} 万元</span>
        </p>
        <p slot="extra">
          <Button size="small" type="primary" @click="addGoal">
            <Icon type="ios-add" />
            添加名目
          </Button>
        </p>
        <Card :bordered="true" style="margin:0 0 10px;" v-for="item,index in goal" :key="index">
          <p slot="title"></p>
          <p slot="extra">
            <Button size="small" type="error" @click="remGoal(index)" v-if="goal.length > 1">
              <Icon type="ios-trash" />
              移除名目
            </Button>
          </p>
          <Row>
            <i-col span="16">
              <FormItem label="安全经费名目" class="ivu-form-item-required">
                <i-input v-model="item.planItemName" placeholder="请填写安全费用名目" clearable/>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="计划使用额（万）" class="ivu-form-item-required">
                <i-input v-model.number="item.planItemAmount" placeholder="请填写计划使用额（万）" clearable @on-change="planActualAmountFun"/>
              </FormItem>
            </i-col>
            <i-col span="24">
              <FormItem label="名目备注">
                <i-input v-model="item.planItemRemark" placeholder="请填写备注" clearable/>
              </FormItem>
            </i-col>
          </Row>
        </Card>

      </Card>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="formOperationFun">取消</Button>
        <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
      </div>
    </Form>

  </div>
</template>
<script>
  /*
  * 1.动态追加安全费用名目
  * 2.申请变量  goal
  * 3.点击添加 goal添加 安全费用名目 和 计划使用数额
  * 4.数据双向绑定
  * 5.删除  根据下坐标删除
  * 6.如果 修改进来 删除if 修改 变量接受删除ID 存储数据
  * */

  export default {
    //modify 修改 add 新增
    // 需要修改的数据  表单类型  打开方式
    props: ["selectdata"],//接收来自父组件的数据
    data() {
      return {
        formData: {
          planStandardPercent: 0.01
        },//表单数据
        ruleValidate: {//正则
          deptUuid: [
            {required: true, message: '请选择运输企业', trigger: 'blur'}
          ],
          wzPlanYear: [
            {type: "date", required: true, message: '请选择年份', trigger: 'blur'}
          ],
          planIncome: [
            {type: 'number', required: true, message: '请填写去年营业额', trigger: 'blur'}
          ],
          planStandardPercent: [
            {type: 'number', required: true, message: '请填写费用提取标准', trigger: 'blur'}
          ],
          planExtractAmount: [
            {type: 'number', required: true, message: '请填写计提安全费用', trigger: 'blur'}
          ],
          planRegistrantName: [
            {required: true, message: '请填写登记人', trigger: 'blur'}
          ],
        },
        goal: [{"planItemName": "", "planItemAmount": "", "planItemRemark": ''}],//动态安全费用名目

        subDeptList: [],//运输企业
        planImgFile: {
          data: null,
          imgUrl: ''
        },
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态
    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      var that = this;
      //运输企业
      that.axios.get(that.apiUrl.subDeptList)
      .then(res => {
        if (!!res) {
          that.subDeptList = res.data.list;
        }
      }).catch(err => {
        console.log("失败", err)
      })


      if (!!!that.selectdata) {
        that.formData = {planStandardPercent: 0.01};//表单
        //安全目标名目
        that.axios.get(that.apiUrl.safetyPlan)
        .then(res => {
          if (!!res) {
            that.goal = [];
            res.data.data.forEach((k, i) => {
              that.goal.push({"planItemName": k.value, "planItemAmount": "", "planItemRemark": ''})
            })
          }
        }).catch(err => {
          console.log("失败", err)
        })
      } else {
        that.axios.get(that.apiUrl.safetyBudgetPlanInfo + that.selectdata.id)
        .then(res => {
          if (!!res) {
            res.data.data.wzPlanYear = new Date(res.data.data.planYear)
            that.formData = res.data.data;//表单
            that.planImgFile.imgUrl = !!that.formData.planImg ? that.apiUrl.imgUrl + that.formData.planImg : '';
            that.goal = that.formData.planItemList;
          }
        }).catch(err => {
          console.log("失败", err)
        })
      }
    },
    methods: {//执行的方法
      //添加安全费用名目
      addGoal() {
        this.goal.push({"planItemName": "", "planItemAmount": "", "planItemRemark": ''})
      },
      //删除安全费用名目
      remGoal(index) {
        this.goal.splice(index, 1);
        this.planActualAmountFun();
      },
      //提交表单
      addSubmit(data) {
        var that = this;

        that.$refs[data].validate((valid) => {
          if (valid) {//正则判断使用
            var data = that.formData;

            delete data.planItemList;

            var formData = new FormData();
            for (var i = 0; i < that.goal.length; i++) {
              if (!!!that.goal[i].planItemName) {
                that.$Message.error('请填写安全费用名目');
                return false;
              }
              if (!!!that.goal[i].planItemAmount && that.goal[i].planItemAmount != 0) {
                that.$Message.error('请填写计划使用额（万）');
                return false;
              }
            }

            data.planItemListStr = JSON.stringify(that.goal);
            data.planYear = that.public.timeFormatting(data.wzPlanYear, "yyyy");



            for (var key in data) {
              if (!!data[key]) {
                formData.append(key, data[key]);
              }
            }

            //图片上传
            !!that.planImgFile.data ? formData.append('planImgFile', that.planImgFile.data) : "";
            that.$Spin.show();//显示加载
            that.axios.post(that.apiUrl.safetyBudgetPlanSaveOrUpdate, formData, {headers: {'Content-Type': "application/x-www-form-urlencoded"}}).then(res => {
              that.$Spin.hide();
              if (!!res) {
                that.$Message.success("数据保存成功");
                that.$emit("closeFun", true)
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {
            this.$Message.error('请正确填写表单');
          }
        })
      },
      //表单关闭
      formOperationFun() {
        this.$emit("closeFun", false)
      },
      //企业名称
      deptNameFun(e) {
        if (!!e) {
          this.formData.deptName = e.label;
        } else {
          this.formData.deptName = "";
        }
      },
      //计算安全费用
      planExtractAmountFun() {
        var that = this;
        if (!!that.formData.planIncome && !!that.formData.planStandardPercent) {
          that.formData.planExtractAmount = parseFloat((parseFloat(that.formData.planIncome) * parseFloat(that.formData.planStandardPercent)).toFixed(2));
        }
      },
      //图片上传
      planImgFileFun(file) {
        var that = this;
        var type = file.type.split("/")[0];
        if (type == "image") {//图片
          that.planImgFile.imgUrl = window.URL.createObjectURL(file);
          that.planImgFile.data = file;
        } else {
          that.$Message.error('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
      //计算实际提取安全费用数额
      planActualAmountFun() {
        var that = this;
        var num = 0;
        for (var i = 0; i < that.goal.length; i++) {
          if (!!that.goal[i].planItemAmount) {
            if (!isNaN(that.goal[i].planItemAmount)) {
              num += that.goal[i].planItemAmount;
            }
          }
        }
        that.formData.planActualAmount = parseFloat(num.toFixed(10));
      },
    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less" scoped>
  ._wz_FundsPlanAdd {
    .demo-drawer-footer {
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      border-top: 1px solid #e8e8e8;
      padding: 10px 16px;
      text-align: right;
      background: #fff;
    }

    .demo-upload-list {
      display: inline-block;
      width: 200px;
      height: 140px;
      text-align: center;
      line-height: 140px;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      border: 1px solid rgba(0, 0, 0, .2);
      margin-right: 4px;

      img {
        width: 100%;
        height: 100%;
      }

      .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);

        i {
          color: #fff;
          font-size: 40px;
          cursor: pointer;
          margin: 0 2px;
        }
      }
    }

    .demo-upload-list:hover .demo-upload-list-cover {
      display: block;
    }
  }


</style>
